package com.bruce.tool.web.filter.config;

import com.bruce.tool.common.util.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Springboot跨域配置
 * @author : Bruce(刘正航) 下午3:23 2018/6/25
 */
@Slf4j
public class CorsConfigurer implements WebMvcConfigurer {

    @Autowired
    private CorsProperties corsProperties;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        if( null == corsProperties || StringUtils.isBlank(corsProperties.getMapping()) ){
            LogUtils.error(log,"跨域配置为空,请检查配置");
            return;
        }
        //配置允许的请求uri地址
        registry.addMapping(corsProperties.getMapping())
                //允许的域名,多个
                .allowedOrigins(corsProperties.getAllowedOrigins())
                //允许的请求方式 "POST", "GET", "PUT", "OPTIONS", "DELETE"
                .allowedMethods(corsProperties.getAllowedMethods())
                //是否允许前端在请求中携带cookie
                .allowCredentials(corsProperties.getAllowCredentials())
                //可以让用户拿到的字段;这几个字段,无论设置与否,前端都可以拿到:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma
                .allowedHeaders(corsProperties.getAllowedHeaders())
                .exposedHeaders(corsProperties.getExposedHeaders())
                //预检请求的有效期，单位为秒。有效期内，不会重复发送预检请求 3600
                .maxAge(corsProperties.getMaxAge());
    }

}